package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusRequest;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.domain.R;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberDto;
import com.zzyl.nursing.dto.QueryDeviceDataDto;
import com.zzyl.nursing.job.Content;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.vo.FamilyMemberVo;
import com.zzyl.nursing.vo.ListByPageVo;
import com.zzyl.nursing.vo.QueryDeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 客户老人家属中间Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-10
 */
@Service
@Slf4j
public class FamilyMemberElderServiceImpl extends ServiceImpl<FamilyMemberElderMapper, FamilyMemberElder> implements IFamilyMemberElderService {
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private Client client;


    @Override
    public List<FamilyMemberVo> getFamilyMemberElder() {
        Long userId = UserThreadLocal.getUserId();
        log.info("用户id：",userId);
        return familyMemberElderMapper.selectrByFamilyMemberId(userId);
    }

    /**
     * 查询客户老人家属中间列表
     *
     * @param familyMemberElder 客户老人家属中间
     * @return 客户老人家属中间
     */
    @Override
    public List<FamilyMemberElder> selectFamilyMemberElderList(FamilyMemberElder familyMemberElder) {
        return familyMemberElderMapper.selectFamilyMemberElderList(familyMemberElder);
    }

    /**
     * 绑定家人
     *
     * @param familyMemberDto 绑定家人
     * @return 结果
     */
    @Override
    public int insertFamilyMemberElder(FamilyMemberDto familyMemberDto) {
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        Long elderId = elderMapper.selectById(familyMemberDto.getIdCard());
        Long userId = UserThreadLocal.getUserId();
        if(ObjectUtil.isEmpty(elderMapper.selectElderById(elderId))){
            log.info("填写身份证有误");
            throw new BaseException("填写身份证有误");
        }
        if(ObjectUtil.isEmpty(elderMapper.selectElderName(familyMemberDto.getName()))){
            log.info("抱歉，没有这个老人的信息");
            throw new BaseException("抱歉，没有这个老人的信息");
        }

        familyMemberElder.setElderId(elderId);
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setRemark(familyMemberDto.getRemark());
        return save(familyMemberElder) ? 1 : 0;
    }

    @Override
    public List<ListByPageVo> selectPage(Integer pageNum, Integer pageSize) {
        Long userId = UserThreadLocal.getUserId();
        IPage page = new Page(pageNum,pageSize);

        LambdaQueryWrapper<FamilyMemberElder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.apply("exists (select 1 from family_member_elder fme " +
                "left join elder e on fme.elder_id = e.id " +
                "left join bed b on b.id = e.bed_id " +
                "left join room r on r.id = b.room_id " +
                "left join device d on d.binding_location = b.id " +
                "where fme.family_member_id = {0})", userId);


        // 使用自定义 SQL 片段
        page = familyMemberElderMapper.selectPageByUserId(page, userId);

        return page.getRecords();
    }

    /**
     * 封装分页信息
     * @param page
     * @return
     */
    private TableDataInfo getTableDataInfo(IPage page) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("请求成功");
        rspData.setRows(page.getRecords());
        rspData.setTotal(page.getTotal());
        return rspData;
    }


    /**
     * 删除客户老人家属中间信息
     *
     * @param id 客户老人家属中间主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberElderById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public Object getDeviceDataByDeviceNameAndProductKey(QueryDevicePropertyStatusRequest request) {

        // 1. 根据 deviceName 和 productKey 查询设备
      request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        try {
            QueryDevicePropertyStatusResponse response = client.queryDevicePropertyStatus(request);
            if(response.getBody().success){
                return response.getBody().getData();
            }
        } catch (Exception e) {
            log.info("调用iot平台获取健康数据失败",e);

        }
        throw new ServiceException("调用iot平台获取健康数据失败");

    }

    @Override
    public List<QueryDeviceDataVo> queryDeviceDataListByDay(QueryDeviceDataDto dto) {
        DateTime start = DateUtil.date(dto.getStartTime());
        DateTime edate = DateUtil.date(dto.getEndTime());
        LocalDateTime startTime = start.toLocalDateTime();
        LocalDateTime endTime = edate.toLocalDateTime();
        String iotId = dto.getIotId();
        String functionId = dto.getFunctionId();

        List<QueryDeviceDataVo> list = familyMemberElderMapper.queryDeviceDataListByDay(startTime,endTime,iotId,functionId);
        return list;
    }

    @Override
    public List<QueryDeviceDataVo> queryDeviceDataListByWeek(QueryDeviceDataDto dto) {
        DateTime start = DateUtil.date(dto.getStartTime());
        DateTime edate = DateUtil.date(dto.getEndTime());
        LocalDateTime startTime = start.toLocalDateTime();
        LocalDateTime endTime = edate.toLocalDateTime();
        String iotId = dto.getIotId();
        String functionId = dto.getFunctionId();

        List<QueryDeviceDataVo> list = familyMemberElderMapper.queryDeviceDataListByWeek(startTime,endTime,iotId,functionId);
        return list;
    }

}
